#include <iostream>
#include <Color/ColorSet.h>
#include <ReduceColor/ReduceColor.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
    auto img_path = "/home/castle/图片/紫月.png";

    auto img = imread(img_path, IMREAD_UNCHANGED);
    auto colorSet = ColorSet();
    cout << "开始提取颜色" << endl;
    for (int i = 0; i < img.rows; i++)
    {
        for (int j = 0; j < img.cols; j++)
        {
            auto p = img.at<Vec4b>(i, j);
            colorSet.AttachColor(Color(p[2], p[1], p[0], p[3], 1));
        }
    }
    cout << "提取颜色完毕" << endl;
    cout << "颜色转列表" << endl;
    auto cList = colorSet.ToList();
    cout << "颜色转列表完毕" << endl;
    cout << "源图色彩数: " << cList.size() << endl;
    unordered_map<Color, uint32_t> cMap;
    unordered_map<uint32_t, Color> pal;
    ReduceColor::MCAReduce(cList, {}, pal, cMap);
    cout << "色盘大小: " << pal.size() << endl;
    auto out = Mat(16, 16, CV_8UC4);
    int count = 0;
    cout << "做输出图像" << endl;
    for (auto& i : pal)
    {
        auto x = count / 16;
        auto y = count % 16;
        (*out.ptr<Vec4b>(x, y))[0] = i.second.b;
        (*out.ptr<Vec4b>(x, y))[1] = i.second.g;
        (*out.ptr<Vec4b>(x, y))[2] = i.second.r;
        (*out.ptr<Vec4b>(x, y))[3] = i.second.a;
        count++;
    }
    cout << "输出图像完毕" << endl;
    auto img_out = Mat();
    img.copyTo(img_out);
    for (int i = 0; i < img_out.rows; i++)
    {
        for (int j = 0; j < img_out.cols; j++)
        {
            auto p = img_out.ptr<Vec4b>(i, j);
            auto order = cMap[Color((*p)[2], (*p)[1], (*p)[0], (*p)[3], 1)];
            auto c = pal[order];
            p->operator[](3) = c.a;
            p->operator[](2) = c.r;
            p->operator[](1) = c.g;
            p->operator[](0) = c.b;
        }
    }
    resize(out, out, Size2i(64, 64), 0, 0, INTER_NEAREST);
    imshow("-1", img);
    imshow("-0.5", img_out);
    imshow("0", out);
    auto w = Mat(img.rows, img.cols * 2, CV_8UC4);
    img.copyTo(w(Rect(0, 0, img.cols, img.rows)));
    img_out.copyTo(w(Rect(img.cols, 0, img.cols, img.rows)));
    out.copyTo(w(Rect(0, 0, 64, 64)));
    imwrite("/home/castle/out.png", w);
    waitKey(0);
    return 0;
}
